﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace MaxLeaf.DAL.W2K
{


    
    public class goods_mainDAL : BaseDAL
    {
        public goods_mainDAL()
            : base()
        {
            strK3TableName = "t_IcItem";
            strWebTableName = "goods_main";

            strK3MapKeyFieldName = "FitemID";
            strWebMapKeyFieldName = "goods_id";
            strWebMapKeyTableName = "k3_goods_main";

            //strK3DestRealKeyFieldName = "FName";
            //strWebOrgDestRealKeyFieldName = "goods_name";


            strFieldNames = "FNumber,FShortNumber,FName,FPOHighPrice,FPOHghPrcMnyType,FWWHghPrc,FWWHghPrcMnyType,FSOLowPrc,FSOLowPrcMnyType,FIsSale,FComCategoryID,FComTypeID,FSellMethod,FComBrandID,FModel,FPointsRate,FVIPPrice,FSilverVIPPrice,FGoldVIPPrice,FBusinessType,FErpClsID,FUnitGroupID,FUnitID,FOrderUnitID,FSaleUnitID,FProductUnitID,FStoreUnitID,FBarCodeUnitID,FKCCUnitID,FSecCoefficient,FQtyDecimal,FLowLimit,FHighLimit,FSecInv,FUseState,FIsEquipment,FIsSparePart,FIsCharSourceItem,FProfitRate,FISKFPeriod,FKFPeriod,FBatchManager,FBookPlan,FCheckCycUnit,FOIHighLimit,FOILowLimit,FSOHighLimit,FSOLowLimit,FInHighLimit,FInLowLimit,FPickHighLimit,FPickLowLimit,FTrack,FPlanPrice,FPriceDecimal,FAcctID,FSaleAcctID,FCostAcctID,FTaxRate,FCostProject,FIsSNManage,FCBRestore,FPlanTrategy,FPlanMode,FOrderTrategy,FFixLeadTime,FLeadTime,FTotalTQQ,FOrderInterVal,FQtyMin,FQtyMax,FBatchAppendQty,FOrderPoint,FBatFixEconomy,FBatChangeEconomy,FBatchSplitDays,FBatchSplit,FRequirePoint,FPlanPoint,FDefaultRoutingID,FDefaultWorkTypeID,FIsBackFlush,FPutInteger,FMRPCon,FMRPOrder,FCtrlType,FKanBanCapability,FIsKeyItem,FGrossWeight,FNetWeight,FMaund,FLength,FWidth,FHeight,FSize,FCubicMeasure,FStandardCost,FCBAppendRate,FStdBatchQty,FStandardManHour,FPieceRate,FInspectionLevel,FProChkMde,FWWChkMde,FSOChkMde,FWthDrwChkMde,FStkChkMde,FOtherChkMde,FSampStdCritical,FSampStdStrict,FSampStdSlight,FStkChkPrd,FStkChkAlrm,FInspectionProject,FExportRate,FImpostTaxRate,FConsumeTaxRate,FIsManage,FManageType,FLenDecimal,FCubageDecimal,FWeightDecimal,FAuxClassID,FSecUnitID,FDefaultLoc,FSPID,FOrderRector,FOrderPrice,FSalePrice,FIsSpecialTax,FStockTime,FBeforeExpire,FAPAcctID,FAdminAcctID,FGoodSpec,FProductPrincipal,FPlanner,FBackFlushStockID,FBackFlushSPID,FDailyConsume,FCBAppendProject,FCostBomID,FCBRouting,FStdPayRate,FChgFeeRate,FStdFixFeeRate,FOutMachFee,FOutMachFeeProject,FPOVAcctID,FPIVAcctID,FMCVAcctID,FPCVAcctID,FSLAcctID,FCAVAcctID,FIdentifier,FHSNumber,FFirstUnitRate,FSecondUnitRate,FCtrlStraregy,FDefaultReadyLoc,FSPIDReady,FPackTypeID,FOperator,FParentID";

            strFItemClassID = Const.FItemClassID_Item;
        }


        public override int Update(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbOrgWebReadCon.CreateCondParam(new Dictionary<string, object>() { { "goods_id", strKeyValue } });
            DataRow drOrg = dbOrgWebReadCon.GetDataFirstRow(string.Format("select goods_id from goods_main where {0}", kvp.Key), kvp.Value);
            if (drOrg == null) throw new MaxLeafException(string.Format("goods_main not exist goods_id {0}", strKeyValue));

            int iDestKey = base.Update(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, strKeyValue);

            string strSql = "UPDATE t1  SET t1.FFullName = t2.FFullName FROM t_ICItemBase t1 INNER JOIN t_Item t2 ON t1.FItemID = t2.FItemID AND t2.FItemID =@FItemID";
            kvp=dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "FItemID", iDestKey.ToString() } });
            dbDestK3Con.ExecuteSql(strSql,kvp.Value);

            return iDestKey;
        }


        protected override void DAL_GetFieldData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strK3FieldName, DataRow drOrgData, DataRow drDestData)
        {
            if (strK3FieldName.Equals("FParentID", StringComparison.InvariantCultureIgnoreCase))
            {
                 if (CvtFunc.ToString(drDestData["FNumber"]).Length == 0)
                {
                    DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, "FNumber", drOrgData, drDestData);
                }
                string strFParentID = GetFParentId(dbDestK3Con, CvtFunc.ToString(drDestData["FNumber"]));
                    drDestData[strK3FieldName] = strFParentID;
                
            }
            else if (strK3FieldName.Equals("FitemID", StringComparison.InvariantCultureIgnoreCase))
            {

                if (CvtFunc.ToInt(drDestData[strK3FieldName]) != 0) return;

                if (CvtFunc.ToString(drDestData["FNumber"]).Length == 0)
                {
                    DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, "FNumber", drOrgData, drDestData);
                }
                string strFParentID = GetFParentId(dbDestK3Con, CvtFunc.ToString(drDestData["FNumber"]));
                //再FitemID
                drDestData[strK3FieldName] = GetFItemID(dbDestK3Con, strFParentID, CvtFunc.ToString(drDestData["FNumber"]), CvtFunc.ToString(drOrgData["goods_name"]));


            }
            else if (strK3FieldName.Equals("FNumber", StringComparison.InvariantCultureIgnoreCase))
            {


                drDestData[strK3FieldName] = GetFNumber(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, drOrgData, drDestData);


            }
            else if (strK3FieldName.Equals("FShortNumber", StringComparison.InvariantCultureIgnoreCase))
            {


                drDestData[strK3FieldName] = GetShortNumber(CvtFunc.ToString(drDestData["FNumber"]));


            }
            else if (strK3FieldName.Equals("FName", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = drOrgData["goods_name"];
            }
            else if (strK3FieldName.Equals("FComCategoryID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = new goods_categoryDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, CvtFunc.ToString(drOrgData["cat_id"]));
            }
            else if (strK3FieldName.Equals("FComBrandID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = new goods_brandDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, CvtFunc.ToString(drOrgData["brand_id"]));
            }    

            else if (strK3FieldName.Equals("FComTypeID", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToInt(drDestData[strK3FieldName]) == 0)
                {
                    drDestData[strK3FieldName] = GetSubMessage(dbDestK3Con, "647", "普通商品");
                }
            }
            else if (strK3FieldName.Equals("FSellMethod", StringComparison.InvariantCultureIgnoreCase))
            {
                if (CvtFunc.ToInt(drDestData[strK3FieldName]) == 0)
                {
                    drDestData[strK3FieldName] = GetSubMessage(dbDestK3Con, "648", "计个");
                }
            }
            else if (strK3FieldName.Equals("FBusinessType", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "36710";
            }
            else if (strK3FieldName.Equals("FUseState", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "341";
            }
            else if (strK3FieldName.Equals("FTrack", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "76";
            }
            else if (strK3FieldName.Equals("FUnitGroupID", StringComparison.InvariantCultureIgnoreCase))
            {
                if (dbDestK3Con.GetDataFirstRow("select FUnitGroupID from t_unitgroup where FUnitGroupID=@FUnitGroupID", new SqlParameter[] { new SqlParameter("@FUnitGroupID", drOrgData["unit_group_id"]) }) != null)
                {
                    drDestData[strK3FieldName] = drOrgData["unit_group_id"];
                }
                else
                {
                    throw new MaxLeafException(string.Format("K3不存在 unit_group_id {0} ", drOrgData["unit_group_id"]));
                }
            }
            else if (strK3FieldName.Equals("FUnitID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = GetUnitId(dbDestK3Con, CvtFunc.ToString(drDestData["FUnitGroupID"]));
            }
            else if (strK3FieldName.Equals("FOrderUnitID", StringComparison.InvariantCultureIgnoreCase)
            || strK3FieldName.Equals("FSaleUnitID", StringComparison.InvariantCultureIgnoreCase)
            || strK3FieldName.Equals("FProductUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FStoreUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FBarCodeUnitID", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FKCCUnitID", StringComparison.InvariantCultureIgnoreCase)
            )
            {
                drDestData[strK3FieldName] = drDestData["FUnitID"];
            }
            else if (strK3FieldName.Equals("FQtyDecimal", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FCubageDecimal", StringComparison.InvariantCultureIgnoreCase)
                )
            {
                drDestData[strK3FieldName] ="4";
            }
            else if (strK3FieldName.Equals("FPriceDecimal", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FLenDecimal", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FWeightDecimal", StringComparison.InvariantCultureIgnoreCase)
            )
            {
                drDestData[strK3FieldName] ="2";
            }
            else if (strK3FieldName.Equals("FAcctID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "1016";
            }
            else if (strK3FieldName.Equals("FSaleAcctID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "1073";
            }
            else if (strK3FieldName.Equals("FCostAcctID", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "1078";
            }
            else if (strK3FieldName.Equals("FTaxRate", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "17";
            }
            else if (strK3FieldName.Equals("FHighLimit", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] ="1000";
            }
            else if (strK3FieldName.Equals("FQtyMax", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "1000";
            }
            else if (strK3FieldName.Equals("FPlanTrategy", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] ="321";
            }
            else if (strK3FieldName.Equals("FPlanMode", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "14036";
            }
            else if (strK3FieldName.Equals("FOrderTrategy", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "331";
            }
            else if (strK3FieldName.Equals("FCtrlType", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "14039";
            }
            else if (strK3FieldName.Equals("FInspectionLevel", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FProChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FWWChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FSOChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FWthDrwChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FStkChkMde", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FOtherChkMde", StringComparison.InvariantCultureIgnoreCase)
                )
            {
                drDestData[strK3FieldName] = "352";
            }
            else if (strK3FieldName.Equals("FStkChkPrd", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = "9999";
            }
            else if (strK3FieldName.Equals("FModel", StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strK3FieldName] = drOrgData["spec"]; ;
            }
                
            else if (strK3FieldName.Equals("FPOHghPrcMnyType", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FWWHghPrcMnyType", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FSOLowPrcMnyType", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FErpClsID", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FCBRestore", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FQtyMin", StringComparison.InvariantCultureIgnoreCase)      
                || strK3FieldName.Equals("FBatchAppendQty", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FBatChangeEconomy", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FRequirePoint", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FPlanPoint", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FMRPCon", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FKanBanCapability", StringComparison.InvariantCultureIgnoreCase)
                || strK3FieldName.Equals("FStdBatchQty", StringComparison.InvariantCultureIgnoreCase) 
                )
            {
                drDestData[strK3FieldName] = 1;
            }
            else
            {
                drDestData[strK3FieldName] = 0;
            }
        }

        private string GetUnitId(DBAccess dbDestK3Con, string strUnitGroupId)
        {
            if (strUnitGroupId.Length == 0 || strUnitGroupId.Equals("0")) return "0";

            string strUnitId = dbDestK3Con.GetValue("select FDefaultUnitID from t_UnitGroup Where FUnitGroupID=@FUnitGroupID"
                , new SqlParameter[]{
                    new SqlParameter("@FUnitGroupID",strUnitGroupId)                    
                }
                );
            if (strUnitId.Length == 0) return "0";

            return strUnitId;
        }

        private string GetSubMessage(DBAccess dbDestK3Con, string strFTypeID, string strFName)
        {
            string strFInterID = dbDestK3Con.GetValue("select FInterID from t_SubMessage Where FInterID>0  AND FDeleted=0  And FTypeID=@FTypeID and FName=@FName"
                ,new SqlParameter[]{
                    new SqlParameter("@FTypeID",strFTypeID)
                    ,new SqlParameter("@FName",strFName)
                }
                );
            if (strFInterID.Length == 0) return "0";

            return strFInterID;
        }


        private string GetFItemID(DBAccess dbDestK3Con, string strFParentID, string strFnumber, string strFName)
        {

            const int intFDetail = 1;

            string strFItemId = string.Empty;
            t_ItemDAL dal = new t_ItemDAL();



            strFItemId = dal.GetFItemId(dbDestK3Con, strFItemClassID, strFnumber.Split('.').Length, strFParentID, strFnumber, strFName, intFDetail);

            UpdateAccess(dbDestK3Con, strFItemId, strFParentID);

            return strFItemId;
        }

        private void UpdateAccess(DBAccess dbDestK3Con, string strFItemId, string strFParentID)
        {
            string strSql = @"
                if not exists(select * from access_t_IcItem where FitemID=@FitemID)
                begin
                 Insert into access_t_IcItem(FitemID,FParentIDX,FDataAccessView,FDataAccessEdit,FDataAccessDelete)
                 Values(@FitemID,@FParentIDX,convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)),convert(varbinary(7200),REPLICATE(char(255),100)))
                end
                ";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@FitemID", strFItemId), new SqlParameter("@FParentIDX", strFParentID) });
        }

        private string GetFNumber(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon,dbDestK3Con, "FComCategoryID", drOrgData, drDestData);

            string strSql = "select FNumber from t_item where FitemID=@FitemID and FItemClassID=@FItemClassID";
            string strParentNumber = dbDestK3Con.GetValue(strSql, new SqlParameter[] { new SqlParameter("@FitemID", drDestData["FComCategoryID"]), new SqlParameter("@FItemClassID", Const.FItemClassID_Category) });
            //if (CvtFunc.ToLeftString(drDestData["FNumber"], strParentNumber.Length + 1).Equals(strParentNumber + "."))
            //{
            //    return CvtFunc.ToString(drDestData["FNumber"]);
            //}
            //else
            //{
            //    return string.Format("{0}.{1}", strParentNumber, GetMaxFNumber(dbDestK3Con, strParentNumber, Const.Len_Category));
            //}
            return string.Format("{0}.{1}", strParentNumber, drOrgData["sku_num"]);
        }


        protected override void WriteK3Log(DBAccess dbDestK3Con, int intKeyValue)
        {
            string strSql = @"insert into mLog(logtype,keyvalue,logstatus)
                values(@logtype,@keyvalue,@logstatus)";
            dbDestK3Con.ExecuteSql(strSql, dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { 
                 {"logtype",LogType.goods_main.ToString()}
                 ,{"keyvalue",intKeyValue.ToString()}
                 ,{"logstatus","1"}
             }).Value);

        }

    }
}